﻿"use strict";
var sealType = 0; //判断拖入的是签名还是签章
var name = ""; //签名图片位置
var sealId = "";
var pfx = 1; //签章选项 第一个还是第二个
var up = 1; //选择签章还是签名
var din = 1; //中心定位还是左上角定位
var first = 1; //关键字的次序，第一次后者最后一次
var idnum = 0; //签章前台对象的id数字
var json = ""; //后台传来的关于pdf文档的签章信息
var region; //当前选中的签章热区域
var sealWH = 119; //缩放比例
var signW = 80; //缩放比例
var signH = 40; //缩放比例
var sealList = null; //印章列表
var pageList = []; //pdf图片列表
var needSavePageSeal = []; //pdf总页数对应的印章列表
var needShowList = []; //需要显示的单页印章数据
var firstPage = {};
var lastPage = {};
var totalPage = null;
var scaleNum = 0.8; //缩放比例
var signToken = "";
var scaleHW = null;//移动端宽高比例无需更改
var scaleWW = "";//移动端缩放比
var sealImgW = "";
var sealImgH = "";

//判断是否是pc还是移动设备
// var cur=null;
function IsPC() {
    var userAgentInfo = navigator.userAgent;
    var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
}



//给移动设备设置的删除签章的方法，后续可删除采用更合适的
function remove() {
    if (idnum > 0) {
        $("#x" + idnum).remove();
        idnum = idnum - 1;
        layui.use('layer', function () {
            var layer = layui.layer;
            layer.msg('最后一个签章或签名已删除', {icon: 1});
        });
    } else {
        layui.use('layer', function () {
            var layer = layui.layer;
            layer.msg('所有签章或签名已删除', {icon: 2});
        });
    }
}

$(document).ready(function () {
    $(".btn-danger").css("display","none");
    $(document).bind("contextmenu", function (e) {
        return false;
    });


   //获完整页数
    $.ajax({
        url: "/sign/pdf/getDocumentPage",
        type: "POST",
        dataType: "json",
        contentType: 'application/json',
        data: JSON.stringify({
            "signToken": signToken,
            "pageNum": "1"
        }),
        success: function success(data) {
            if (data.code === "w0000") {
                
                totalPage = data.data.pageNumTotal;

            } else {
                var conAlert = "<div>\n\t    <div style=\"margin: 20px 0 20px 0;\">获取pdf数据失败</div>\n\t                        <p>" + data + "</p>\n                        </div>";
                jConfirm('', conAlert, '确定', function () {
                }, function (e) {
                });
            }
        },
        async: false,
        error: function error() {
        }
    });




    //获取pdf文档页数和数据
    //获取第一页的pdf数据
    //console.log(signToken);

    $.ajax({
         url: "/sign/pdf/getDocumentPage",
         type: "POST",
         dataType: "json",
         contentType: 'application/json',
         data: JSON.stringify({
             "signToken": signToken,
            "pageNum": "1"
         }),
         success: function success(data) {
             if (data.code === "w0000") {
                 // firstPage.pageImge = "data:image/png;base64," + data.data.pageImge;
                 firstPage.pageImge = "/sign/pdf/getDocumentPageImg?token=" + signToken + "&pageNum=" + 1;
    
                 scaleHW = (parseInt(data.data.pageHight) / parseInt(data.data.pageWidth)).toFixed(1);
                 var ttt = parseInt(data.data.pageWidth) / 25.4 * 96 * scaleNum
                 scaleWW = (document.body.clientWidth / ttt).toFixed(4)
    
    
                if (IsPC()) {
                     firstPage.pageWidth = parseInt(data.data.pageWidth) / 25.4 * 96 * scaleNum;
                     firstPage.pageHight = parseInt(data.data.pageHight) / 25.4 * 96 * scaleNum;
                 } else {
    
                     firstPage.pageWidth = document.body.clientWidth;
                     firstPage.pageHight = document.body.clientWidth * scaleHW;
                 }
                 firstPage.pageNumTotal = data.data.pageNumTotal;
    
             } else {
                 var conAlert = "<div>\n\t    <div style=\"margin: 20px 0 20px 0;\">获取pdf数据失败</div>\n\t                        <p>" + data + "</p>\n                        </div>";
                 jConfirm('', conAlert, '确定', function () {
                 }, function (e) {
                 });
             }
         },
         async: false,
         error: function error() {
         }
     });




   
    pageList.push({currentPage: 1, data: firstPage});
    var sealStr = "<div class=\"page\">\n            <img alt=\"\" width=\"" + pageList[0].data.pageWidth + "\" height=\"" + pageList[0].data.pageHight + "\" page=\"1\" class=\"pic\" src=\"" + pageList[0].data.pageImge + "\" >\n        </div>";
    $("#view").append(sealStr);
    //分页
    $('.pagination').jqPagination({
        link_string: '/?page={page_number}',
	current_page: 1, // 设置当前页 默认为 1
        max_page: parseInt(totalPage),
        page_string: '{current_page}/{max_page}页',
        paged: function paged(page) {
            //console.log("当前第" + page);
            //请求第第n页数据
            var nPage = {};
            $.ajax({
                url: "/sign/pdf/getDocumentPage",
                type: "POST",
                dataType: "json",
                contentType: 'application/json',
                data: JSON.stringify({
                    "signToken": signToken,
                    "pageNum": page
                }),
                success: function success(data) {
                    if (data.code === "w0000") {
                        // nPage.pageImge = "data:image/png;base64," + data.data.pageImge;
			
                        nPage.pageImge = "/sign/pdf/getDocumentPageImg?token=" + signToken + "&pageNum=" + page;


                        //const scaleHW = (parseInt(data.data.pageHight)/parseInt(data.data.pageWidth)).toFixed(1);
                        if (IsPC()) {
                            nPage.pageWidth = parseInt(data.data.pageWidth) / 25.4 * 96 * scaleNum;
                            nPage.pageHight = parseInt(data.data.pageHight) / 25.4 * 96 * scaleNum;
                        } else {
                            nPage.pageWidth = document.body.clientWidth;
                            nPage.pageHight = document.body.clientWidth * scaleHW;
                        }
                        nPage.pageNumTotal = data.data.pageNumTotal;
                    } else {
                        var conAlert = "<div>\n\t   <div style=\"margin: 20px 0 20px 0;\">获取pdf数据失败</div>\n\t                        <p>" + data + "</p>\n                        </div>";
                        jConfirm('', conAlert, '确定', function () {
                        }, function (e) {
                        });
                    }
                },
                async: false,
                error: function error() {
                }
            });

            if (pageList.length < parseInt(page)) {
                pageList.push({currentPage: parseInt(page), data: nPage});
            }

            for (var i = 0; i < pageList.length; i++) {
                if (pageList[i].currentPage == page) {
                    $("img.pic").attr("src", pageList[i].data.pageImge);
                    $("img.pic").attr("page", page);
                }
            }

            $('.page').children().not(':first-child').hide();
            for (var _i = 0; _i < needSavePageSeal.length; _i++) {
                if (page == needSavePageSeal[_i].page) {
                    //needShowList.push(needSavePageSeal[i].sealData);
                    needSavePageSeal[_i].sealData.style.display = "inline";
                    //$(".page").append(needSavePageSeal[i].sealData);

                } else {
                }
            }
        }
    });
    $("#addSeal").click(function (event) {
        var imgLi = '';
        //获取印章列表
        $.ajax({
            url: "/sign/pdf/getSealListBySignToken",
            type: "POST",
            dataType: "json",
            contentType: 'application/json',
            data: JSON.stringify({
                "signToken": signToken,
                "imgType": "1"
            }),
            success: function success(data) {
                if (data.code === "w0000") {
                    sealList = data.msg;
                    //console.log(data);
                } else {
                    var conAlert = "<div>\n\t   <div style=\"margin: 20px 0 20px 0;\">获取印章列表数据失败</div>\n\t                        <p>" + data + "</p>\n                        </div>";
                    jConfirm('', conAlert, '确定', function () {
                    }, function (e) {
                    });
                }
            },
            async: false,
            error: function error() {
            }
        });

        for (var i = 0; i < sealList.length; i++) {
            imgLi += "<li><a href=\"#\"><img src=\"\" sealid=" + sealList[i].sealId + "></a></li>";
        }

        var alertStr = "<div class=\"banner\">\n\t                        <div class=\"banner-btn\">\n\t\t                        <a href=\"javascript:;\" class=\"prevBtn\"><i></i></a>\n\t\t                        <a href=\"javascript:;\" class=\"nextBtn\"><i></i></a>\n\t                        </div>\n\t                        <ul class=\"banner-img\">\n                               " + imgLi + "\n\t                        </ul>\n\t                        <ul class=\"banner-circle\"></ul>\n                        </div>";

        jConfirm('', alertStr, '确定', function () {
            // 获取第一张图片
            $.ajax({
                url: "/sign/pdf/getSealImgBySealId",
                type: "POST",
                dataType: "json",
                contentType: 'application/json',
                data: JSON.stringify({
                    "signToken": signToken,
                    "sealId": sealList[0].sealId
                }),
                success: function success(data) {
                    if (data.code === "w0000") {
                        //console.log(data);
                        sealImgW = parseInt(data.msg.imgWidth) / 25.4 * 96 * scaleNum;
                        sealImgH = parseInt(data.msg.imgHeight) / 25.4 * 96 * scaleNum;
                        $(".banner-img img")[0].setAttribute("src", "data:image/png;base64," + data.msg.imgBase64);
                        $(".banner-img img")[0].setAttribute("width", sealImgW);
                        $(".banner-img img")[0].setAttribute("height", sealImgH);

                    } else {
                        var conAlert = "<div>\n\t   <div style=\"margin: 20px 0 20px 0;\">获取印章列表数据失败</div>\n\t                        <p>" + data + "</p>\n                        </div>";
                        jConfirm('', conAlert, '确定', function () {
                        }, function (e) {
                        });
                    }
                },
                async: false,
                error: function error() {
                }
            });
        }, function (e) {
            var arrLi = $(".banner-circle li");
            for (var _i2 = 0; _i2 < arrLi.length; _i2++) {
                if (arrLi[_i2].getAttribute("class") === "selected") {
                    (function () {

                        $(".page").css({width: $(".page").children("img").get(0).width});
                        $(".page").css({height: $(".page").children("img").get(0).height});
                        var sealTarget = $(".banner-img img")[_i2];
                        // var sealCss = "position:absolute;top:200px;left:200px;";
                        var indexI = 0;
                        if (!$(".page img:last").attr("sealid")) {
                            indexI = 0;
                        } else {
                            //每新增一个印章盒子里的最后一个印章id++
                            indexI = parseInt($("div img:last-of-type").attr("id").replace(/[^0-9]/ig, "")) + 1;
                        }

                        sealTarget.setAttribute("id", "pageSeal" + indexI);
                        sealTarget.setAttribute("class", "ui-widget-header");
                        sealTarget.setAttribute("page", $(".page img")[0].getAttribute("page"));
                        // sealTarget.style = sealCss;
                        sealTarget.style.position = "absolute";
                        sealTarget.style.top = "200px";
                        sealTarget.style.left = "200px";


                        $(".page").append(sealTarget);
                        $(".page").addClass("draggable");
                        $(".page").addClass("ui-widget-content");
                        $("#pageSeal" + indexI).draggable({
                            containment: "parent",
                            cursor: "move"

                        });
                        needSavePageSeal.push({page: $(".page img")[0].getAttribute("page"), sealData: sealTarget});
                        $("#pageSeal" + indexI).doubleTap(function () {
                            for (var _i3 = 0; _i3 < needSavePageSeal.length; _i3++) {
                                if ($("#pageSeal" + indexI).attr("sealid") === needSavePageSeal[_i3].sealData.getAttribute("sealid")) {
                                    needSavePageSeal.splice(_i3, 1);
                                    $("#pageSeal" + indexI).remove();
                                    if(needSavePageSeal.length <= 0){
                                        $(".btn-danger").css("display","none");
                                    }
                                }
                            }
                        });
                        //把确认签章开关打开
                        $(".btn-danger").css("display","inline-block");



                    })();
                }
            }
        });
        //轮播
        $(function () {
            var $banner = $('.banner');
            var $banner_ul = $('.banner-img');
            var $btn = $('.banner-btn');
            var $btn_a = $btn.find('a');
            var v_width = $banner.width();

            var page = 1;

            var timer = null;
            var btnClass = null;

            var page_count = $banner_ul.find('li').length; //把这个值赋给小圆点的个数

            var banner_cir = "<li class='selected' href='#'><a></a></li>";
            for (var i = 1; i < page_count; i++) {
                //动态添加小圆点
                banner_cir += "<li><a href='#'></a></li>";
            }
            $('.banner-circle').append(banner_cir);

            var cirLeft = $('.banner-circle').width() * -0.5;
            $('.banner-circle').css({'marginLeft': cirLeft});

            $banner_ul.width(page_count * v_width);

            function move(obj, classname) {
                //手动及自动播放
                if (!$banner_ul.is(':animated')) {
                    if (classname == 'prevBtn') {
                        if (page == 1) {
                            $banner_ul.animate({left: -v_width * (page_count - 1)});
                            page = page_count;
                            cirMove();
                        } else {
                            $banner_ul.animate({left: '+=' + v_width}, "slow");
                            page--;
                            cirMove();
                        }
                    } else {
                        if (page == page_count) {
                            $banner_ul.animate({left: 0});
                            page = 1;
                            cirMove();
                        } else {
                            $banner_ul.animate({left: '-=' + v_width}, "slow");
                            page++;
                            cirMove();
                        }
                    }
                }
            }

            function cirMove() {
                //检测page的值，使当前的page与selected的小圆点一致
                $('.banner-circle li').eq(page - 1).addClass('selected').siblings().removeClass('selected');
            }

            $banner.mouseover(function () {
                $btn.css({'display': 'block'});
                //clearInterval(timer);
            }).mouseout(function () {
                $btn.css({'display': 'block'});
                // clearInterval(timer);
                // timer=setInterval(move,3000);
            }).trigger("mouseout"); //激活自动播放

            $btn_a.mouseover(function () {
                //实现透明渐变，阻止冒泡
                $(this).animate({opacity: 0.6}, 'fast');
                $btn.css({'display': 'block'});
                return false;
            }).mouseleave(function () {
                $(this).animate({opacity: 0.3}, 'fast');
                $btn.css({'display': 'block'});
                return false;
            }).click(function () {

                //手动点击清除计时器
                btnClass = this.className;
                // clearInterval(timer);
                // timer=setInterval(move,3000);
                move($(this), this.className);
                if (this.getAttribute("class") === "nextBtn") {
                    setImgData();
                } else if (this.getAttribute("class") === "prevBtn") {
                    setImgData();
                }
                //console.log(this.getAttribute("class"));
            });

            //设置印章数据
            function setImgData() {
                var _loop = function _loop(_i4) {
                    if ($(".banner-circle li")[_i4].getAttribute("class") === "selected") {
                        $.ajax({
                            url: "/sign/pdf/getSealImgBySealId",
                            type: "POST",
                            dataType: "json",
                            contentType: 'application/json',
                            data: JSON.stringify({
                                "signToken": signToken,
                                "sealId": sealList[_i4].sealId
                            }),
                            success: function success(data) {
                                if (data.code === "w0000") {
                                    //如果src不为空就不请求了
                                    if ($(".banner-img img")[_i4].getAttribute("src") === "") {
                                        $(".banner-img img")[_i4].setAttribute("src", "data:image/png;base64," + data.msg.imgBase64);
                                        if (IsPC()) {
                                            $(".banner-img img")[_i4].setAttribute("width", parseInt(data.msg.imgWidth) / 25.4 * 96 * scaleNum);
                                            $(".banner-img img")[_i4].setAttribute("height", parseInt(data.msg.imgHeight) / 25.4 * 96 * scaleNum);
                                        } else {
                                            $(".banner-img img")[_i4].setAttribute("width", parseInt(data.msg.imgWidth) / 25.4 * 96 * scaleNum * scaleWW);
                                            $(".banner-img img")[_i4].setAttribute("height", parseInt(data.msg.imgHeight) / 25.4 * 96 * scaleNum * scaleWW);
                                        }

                                    }
                                } else {
                                    var conAlert = "<div>\n\t  <div style=\"margin: 20px 0 20px 0;\">获取印章数据失败</div>\n\t                                                    <p>" + data + "</p>\n                                                        </div>";
                                    jConfirm('', conAlert, '确定', function () {
                                    }, function (e) {
                                    });
                                }
                            },
                            async: false,
                            error: function error() {
                            }
                        });
                    }
                };

                for (var _i4 = 0; _i4 < $(".banner-circle li").length; _i4++) {
                    _loop(_i4);
                }
            }

            $('.banner-circle li').click(function () {
                var index = $('.banner-circle li').index(this);
                $banner_ul.animate({left: -v_width * index}, 'slow');
                page = index + 1;
                cirMove();
                setImgData();
            });
        });


    });
    $(".btn-danger").click(function () {

        // if (needSavePageSeal.length <= 0) {
        //     var conAlert = "<div><div style=\"margin: 20px 0 20px 0;\">请先在pdf上进行签章</div><p></p></div>";
        //     jConfirm('', conAlert, '确定', function () {
        //     }, function (e) {
        //     });
        //     return;
        // }




        var alertStr = "<div>\n\t   <div style=\"margin: 20px 0 20px 0;\">是否确认进行签章？</div>\n   </div>";
        jConfirm('', alertStr, '确定', function () {
        }, function (e) {
            var tmpSealList = [];
            for (var i = 0; i < needSavePageSeal.length; i++) {
                var t = {};
                t.pageNum = needSavePageSeal[i].page;
                t.sealId = needSavePageSeal[i].sealData.getAttribute("sealid");


                if (IsPC()) {
                    var sX = parseInt(needSavePageSeal[i].sealData.style.left.split("px")[0]);
                    var sY = parseInt(needSavePageSeal[i].sealData.style.top.split("px")[0]);
                    var sWidth = parseInt(needSavePageSeal[i].sealData.width);
                    var sHeight = parseInt(needSavePageSeal[i].sealData.height);
                    var pWidth = parseInt($(".page").width());
                    var pHeight = parseInt($(".page").height());
                    t.X = (sX + sWidth / 2) / 96 * 25.4 / scaleNum;
                    t.Y = (pHeight + 2 - sY - sHeight / 2) / 96 * 25.4 / scaleNum;
                } else {

                    var sX = parseInt(needSavePageSeal[i].sealData.style.left.split("px")[0]);
                    var sY = parseInt(needSavePageSeal[i].sealData.style.top.split("px")[0]);
                    var sWidth = parseInt(needSavePageSeal[i].sealData.width);
                    var sHeight = parseInt(needSavePageSeal[i].sealData.height);
                    var pWidth = parseInt($(".page").width());
                    var pHeight = parseInt($(".page").height());
                    t.X = (sX + sWidth / 2) / 96 * 25.4 / scaleNum / scaleWW;
                    t.Y = (pHeight + 2 - sY - sHeight / 2) / 96 * 25.4 / scaleNum / scaleWW;
                }
                tmpSealList.push(t);
            }
            // //开始签章
            var usrT = IsPC() ? "/sign/pdf/dragSign" : "/sign/pdf/dragSign/dragSignMobile";

            //alert(usrT)
            $.ajax({
                url: usrT,
                type: "POST",
                dataType: "json",
                contentType: 'application/json',
                data: JSON.stringify({
                    "signToken": signToken,
                    "seals": tmpSealList
                }),
                success: function success(data) {
//alert(data.code,data.url)
                    //console.log(data);
                    var conAlert = "<div>\n\t  <div style=\"margin: 20px 0 20px 0;\">" + (data.code === "0000" && tmpSealList.length > 0 ? "签章成功，点击确定退出" : "签章失败，请重试") + "</div>\n                        </div>";
                    jConfirm('', conAlert, '确定', function () {
                    }, function (e) {
                        if (data.code === "0000") {
                            if (IsPC()) {
                                window.open("about:blank", "_self").close();
                            } else if (data.url === "") {
                                window.history.go(-2);
                            } else {
                                window.location.href = data.url;
                            }
                        } else {
                            var _conAlert = "<div>\n\t <div style=\"margin: 20px 0 20px 0;\">签章失败</div><p>" + data + "</p>\n  </div>";
                            jConfirm('', _conAlert, '确定', function () {
                            }, function (e) {
                            });
                        }
                    });
                },
                async: false,
                error: function error() {
                }
            });
        });
    });
});
